package com.example.mybatisplus.controller;

import com.example.mybatisplus.common.JsonResponse;
import com.example.mybatisplus.model.domain.VisitLog;
import com.example.mybatisplus.service.ConsultMergeService;
import com.example.mybatisplus.service.SingleTimeService;
import com.example.mybatisplus.service.UserService;
import com.example.mybatisplus.service.VisitLogService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.example.mybatisplus.common.Constants.ROLE_FIRSTVISIT;


@RestController
@RequestMapping("/api/visitLog")
public class VisitLogController {

    private final Logger logger = LoggerFactory.getLogger( VisitLogController.class );

    @Autowired
    private VisitLogService visitLogService;

    @Autowired
    private UserService userService;

    @Autowired
    private SingleTimeService singleTimeService;

    @Autowired
    private ConsultMergeService consultMergeService;

    /**
     * 为预约中的初访记录安排初访
     */
    @GetMapping("/status/inprogress/{id}/{teacherId}")
    public JsonResponse inprogress(@PathVariable("id") Long id,@PathVariable("teacherId") Long teacherId){
        System.out.println(id+"  "+teacherId);
        try{
            visitLogService.onProgress(id,teacherId);
            return JsonResponse.success().setMessage("预约中的初访安排成功");
        } catch (Exception e){
            return JsonResponse.failure("预约中的初访安排失败");
        }
    }


    @RequiresRoles("咨询师")
    @GetMapping("")
    public JsonResponse show(){
        return JsonResponse.success(visitLogService.list(),"查询成功");
    }




    @RequestMapping(value = {"/{id}"}, method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getById(@PathVariable("id") Long id)throws Exception {
        VisitLog  visitLog =  visitLogService.getById(id);
        return JsonResponse.success(visitLog);
    }



    @GetMapping("/delete/{id}")
    @ResponseBody
    public JsonResponse deleteById(@PathVariable("id") Long id) throws Exception {
        visitLogService.removeById(id);
        return JsonResponse.success(null).setMessage("删除成功");
    }




    @RequestMapping(value ="" , method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateVisitLog(VisitLog  visitLog) throws Exception {
        visitLogService.updateById(visitLog);
        return JsonResponse.success(null);
    }



    @PostMapping("")
    public JsonResponse create(@RequestBody Map<Object,Object> request) throws Exception {
        try{
            System.out.println(request);
            String username = request.get("stuName").toString();
            String teacherName = request.get("teacherName").toString();
            Map<Object,Object> temp = (Map<Object, Object>) request.get("Time");
            String time = temp.get("Time").toString();
            String week = temp.get("Week").toString();
            Long stuId = userService.getIdByName(username);
            System.out.println("stuid "+stuId+" "+username);
//            Long teacherId = userService.getTeacherIdByName(teacherName);
            Long teacherId = userService.getByNameAndType(teacherName, ROLE_FIRSTVISIT);

            System.out.println("teacherId "+teacherId+ " "+teacherName);
            Long timeId = singleTimeService.getIdByTime(time,week);
            System.out.println("time "+timeId);
            Date start = consultMergeService.getStarttime(timeId);
            if(stuId==null||teacherId==null||timeId==null){
                throw new Exception();
            }
            VisitLog visitLog = new VisitLog();
            visitLog.setStuId(stuId).setTeaId(teacherId).setTimeId(timeId).setStartTime(start);
            System.out.println(visitLog);
            Date date = new Date();
            visitLog.setCreatedTime(date);
            visitLogService.save(visitLog);
            return JsonResponse.success().setMessage("新增成功");
        } catch (Exception e){
            return JsonResponse.failure("新增失败 "+e.getMessage());
        }
    }


    /**
     * 描述:根据当前用户名查询初访预约记录+++
     * */

    @RequestMapping(value = "/getvisitlogbystuusername/{stuusername}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getvisitlogbystuusername(@PathVariable("stuusername") String stuusername){
        VisitLog visitLog=visitLogService.getvisitlogbystuusername(stuusername);
        if (visitLog==null){
            return JsonResponse.failure("无初访预约记录");
        }
        else {
            return JsonResponse.success().setMessage("查询成功").setData(visitLog);
        }
    }
    /**
     * 描述:根据问卷分数改动心理状态，心理疾病学生自动生成初始初访记录，所有学生的分数存入问卷表+++
     *
     * */
    @RequestMapping(value = "/savestatus/{name}/{grade}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse savestatus(@PathVariable("name") String stuusername,@PathVariable ("grade")Integer  grade) throws Exception {
        String message=visitLogService.savestatus(grade,stuusername);
        return JsonResponse.success().setMessage(message);
    }

    /**
     * 描述：当初访记录存在时，学生在前端可修改时间，初访师，(状态位为是否完成初访，0表示未完成，1表示完成。默认为0)+++
     * */
    @RequestMapping(value = "/updateTimeandTeacher", method = RequestMethod.PUT)
    @ResponseBody
    public JsonResponse updateTimeandTeacher(@RequestBody VisitLog  visitLog) throws Exception {
        String message=visitLogService.updateTimeandTeacher(visitLog.getTimeId(),visitLog.getTeaId(),visitLog.getStuId());
        return JsonResponse.success().setMessage(message);
    }



    /**
     *描述：中心管理员查询所有的初访记录（分页查询）+++
     **/
    @RequestMapping(value = "/getall", method = RequestMethod.GET)
    @ResponseBody

    public JsonResponse getallVisitlog()throws Exception {
        List<VisitLog> visitLogs=visitLogService.getallVisitlog();
        return JsonResponse.success().setMessage("查询成功").setData(visitLogs);
    }

    /***
     * 描述：中心管理员逻辑删除初访记录
     */
    @RequestMapping(value = "/deletebyId", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse deletebyId(@RequestBody List<VisitLog> visitLogs ) throws Exception {

        List<Long> t = new ArrayList<>();
        for(VisitLog v : visitLogs){
            t.add(v.getId());
        }
        visitLogService.removeByIds(t);

//        visitLogService.deleteFaker(resMap);
        return JsonResponse.success().setMessage("批量删除成功");
    }


    /**
     * 描述：初访师查询自己的病人+++
     * */
    @RequestMapping(value = "/getpatientbyTeaId", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getpatientbyTeaId() throws Exception {
        //
        //认证教师
        //
        List<VisitLog> visitLogs=visitLogService.getpatientbyTeaId();
        return JsonResponse.success().setMessage("查询成功").setData(visitLogs);
    }

    /**
     *学生首页显示自己的初访记录
     */
    @RequestMapping(value = "/getStuVisitLog",method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getStuVisitLog(Long stuId) throws Exception{
        List<VisitLog> visitLogs = visitLogService.queryVisitLog(stuId);
        List<Map<String,String>> resVisitLog = new ArrayList<>();
        for(VisitLog visitLog:visitLogs){
            resVisitLog.add(packageVisitLog(visitLog));
        }
        return JsonResponse.success(resVisitLog);
    }

    public Map<String,String> packageVisitLog(VisitLog visitLog){
        Map<String,String> resMap = new HashMap<>();
        Date start_time = visitLog.getStartTime();
        Calendar cal = Calendar.getInstance();
        cal.setTime(start_time);
        try{
            resMap.put("stu_name",userService.getById(visitLog.getStuId()).getStuName());
            resMap.put("tea_name",userService.getById(visitLog.getTeaId()).getStuName());
            resMap.put("start_time",new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
        }catch (Exception e){
            return resMap;
        }
        return resMap;
    }
}

